package com.wyc.serviceMap.remote;

import com.wyc.internalCommon.constant.AmapConfigConstant;
import com.wyc.internalCommon.response.ServiceResponse;
import com.wyc.internalCommon.result.ApiResult;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 调用高德猎鹰轨迹服务Api业务层
 */
@Service
public class ServiceClient {

    @Value("${amap.key}")
    private String amapKey;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 创建轨迹服务，获取到sid（服务id）
     * @param name
     * @return
     */
    public ApiResult add(String name){
        // 拼接路径url
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(AmapConfigConstant.SERVICE_ADD_URL_PREFIX);
        urlBuilder.append("?");
        urlBuilder.append("key="+amapKey);
        urlBuilder.append("&");
        urlBuilder.append("name="+name);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(urlBuilder.toString(), null, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSONObject.fromObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        String sid = data.getString("sid");

        ServiceResponse serviceResponse = new ServiceResponse();
        serviceResponse.setSid(sid);

        return ApiResult.success(serviceResponse);

    }

}
